package com.example.pictureview.widget;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.OrientationEventListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.MediaController;
import android.widget.VideoView;

import com.example.pictureview.R;

import static android.content.Context.POWER_SERVICE;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

/**
 * Created by Administrator on 2017/7/27 0027.
 */

public class VideoHelper {
//    static final int INIT = 0;

    static final int TYPE_LANDSPACE = 0x001;
    static final int TYPE_RESERVE = 0x002;
    static final int TYPE_FORCE = 0x004;

    static final int PROTRAIT = 0;
    static final int RESERVE_PORTRAIT = PROTRAIT | TYPE_RESERVE;
    static final int LANDSPACE = TYPE_LANDSPACE;
    static final int RESERVE_LANDSCAPE = LANDSPACE | TYPE_RESERVE;


    static final int LANDSPACE_MASK = TYPE_LANDSPACE;
    static final int ROTATE_MASK = LANDSPACE | TYPE_RESERVE;
    static final int FORCE_MASK = TYPE_FORCE;
    static final int FORCE_ROTATE_MASK = ROTATE_MASK | FORCE_MASK;


    private Activity mActivity;
    private VideoView mVideoView;
//    private MediaController mController;
    private OrientationEventImpl mOrientation = null;
//    private boolean mIsLandspace;

    private int mScreenFlag = PROTRAIT;
//    private boolean mIsAutoRotateScreen;

    private RotationObserver mRotationObserver;
    private PowerManager.WakeLock mWakeLock;
    private int mCurrentPosition;

    public VideoHelper(Activity activity, VideoView view, MediaController controller) {
        mActivity = activity;
        mVideoView = view;
//        mVideoView.setOnInfoListener(mOnInfoListener);
//        mVideoView.setOnPreparedListener(mOnPreparedListener);
//        mVideoView.setOnCompletionListener(mOnCompletionListener);
//        mVideoView.setOnErrorListener(mOnErrorListener);
//        mController = controller;
//        ((MediaControllerView) mController).setOnFullListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                rotateScreen();
//            }
//        });
//        mVideoView.setMediaController(mController);
        mOrientation = new OrientationEventImpl(activity.getApplicationContext());
        mRotationObserver = new RotationObserver(mActivity, mOrientation, null);
        PowerManager power = (PowerManager) mActivity.getSystemService(POWER_SERVICE);
        mWakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Lock");
    }

    public void onResume() {
        mWakeLock.acquire();
        mVideoView.seekTo(mCurrentPosition);
        if (!mVideoView.isPlaying()) {
            mVideoView.start();
        }
        mRotationObserver.startObserver();
//        mController.show();
//        mOrientation.enable();
    }

    public void onPause() {

//        mVideoView.pause();
//        mVideoView.pause();
//        mVideoView.release(false);
        mCurrentPosition = mVideoView.getCurrentPosition();
        if (mVideoView.isPlaying()) {
            mVideoView.pause();
        }
        mRotationObserver.stopObserver();
        if (mWakeLock.isHeld()) {
            mWakeLock.release();
        }
//        mController.hide();
//        mOrientation.disable();
    }

    public void onConfigurationChanged(Configuration newConfig) {
        resetLayoutParams(newConfig.orientation);
    }

    public boolean onBackPressed() {
        if ((mScreenFlag & LANDSPACE_MASK) == LANDSPACE) {
            rotateScreenInternal(PROTRAIT);
            mScreenFlag = TYPE_FORCE | PROTRAIT;
            return false;
        }
        return true;
    }


    public void onDestory() {
        mVideoView.stopPlayback();
    }


    private final String TAG = getClass().getSimpleName();

    private void resetLayoutParams(int orientation) {
        Log.i(TAG, "@@" + orientation + "," + mActivity.getRequestedOrientation());


        FrameLayout.LayoutParams videoParams = null;
//        RelativeLayout.LayoutParams controlLayout = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (orientation == SCREEN_ORIENTATION_PORTRAIT) {
            videoParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mActivity.getResources().getDimensionPixelSize(R.dimen.video_portrait_height), Gravity.CENTER);

        } else {

            videoParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER);

        }
        mVideoView.setLayoutParams(videoParams);
    }

    private class OrientationEventImpl extends OrientationEventListener {

        public OrientationEventImpl(Context context) {
            super(context);
        }

        @Override
        public void onOrientationChanged(int orientation) {

            if (orientation == ORIENTATION_UNKNOWN) {
                return;
            }


            int newFlag = mScreenFlag & (~ROTATE_MASK);
            if (orientation >= 337 || orientation < 23) {
                newFlag |= PROTRAIT;
            } else if (orientation >= 67 && orientation < 113) {
                newFlag |= RESERVE_LANDSCAPE;
            } else if (orientation >= 157 && orientation < 203) {
                return;
            } else if (orientation >= 247 && orientation < 293) {
                newFlag |= LANDSPACE;
            } else {
                return;
            }

            if (mScreenFlag != newFlag) {
//                Log.i(TAG, "@@@@:" + Integer.toBinaryString(mScreenFlag));
//                Log.i(TAG, "@@@#:" + Integer.toBinaryString(newFlag));

                int forceFlag = mScreenFlag & FORCE_MASK;
                if (forceFlag == TYPE_FORCE) {
//                    Log.i(TAG, "@@@#:no");
                    return;
                }


                rotateScreenInternal(newFlag);
                mScreenFlag = newFlag;

            } else {
                mScreenFlag &= ~FORCE_MASK;
            }


        }
    }

    public void rotateScreen() {
        switch (mScreenFlag & ROTATE_MASK) {
            case LANDSPACE:
            case RESERVE_LANDSCAPE:
                rotateScreenInternal(PROTRAIT);
                mScreenFlag = TYPE_FORCE | PROTRAIT;
                break;
            case PROTRAIT:
            case RESERVE_PORTRAIT:
                rotateScreenInternal(LANDSPACE);
                mScreenFlag = TYPE_FORCE | LANDSPACE;
                break;
        }
    }


    private void rotateScreenInternal(int flag) {
        switch (ROTATE_MASK & flag) {
            case LANDSPACE:
                mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                break;
            case RESERVE_LANDSCAPE:
                mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                break;
            case PROTRAIT:
                mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
            default:
                break;
        }
    }

//    private IMediaPlayer.OnPreparedListener mOnPreparedListener = new IMediaPlayer.OnPreparedListener() {
//        @Override
//        public void onPrepared(IMediaPlayer iMediaPlayer) {
//            Log.i(TAG,"@@onPrepared");
//
//        }
//    };
//    private IMediaPlayer.OnCompletionListener mOnCompletionListener = new IMediaPlayer.OnCompletionListener() {
//        @Override
//        public void onCompletion(IMediaPlayer iMediaPlayer) {
//            Log.i(TAG,"@@onCompletion");
//        }
//    };
//    private IMediaPlayer.OnInfoListener mOnInfoListener = new IMediaPlayer.OnInfoListener() {
//        @Override
//        public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
//            Log.i(TAG,"@@onInfo");
//            return false;
//        }
//    };
//    private IMediaPlayer.OnErrorListener mOnErrorListener = new IMediaPlayer.OnErrorListener() {
//        @Override
//        public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
//            Log.i(TAG,"@@onError");
//            return false;
//        }
//    };


}
